class Utility {
    static maxNumber() {
        let numbers = Array.from(arguments).filter(arg => {
            return !isNaN(parseInt(arg, 10));
        });
        if (numbers.length == 0) {
            throw Error('No max number');
        }
        return Math.max(...numbers);
    }

    static minNumber() {
        let numbers = Array.from(arguments).filter(arg => {
            return !isNaN(parseInt(arg, 10))
        });
        if (numbers.length == 0) {
            throw Error('No min number');
        }
        return Math.min(...numbers);
    }

    /**
     *  获得指定范围的随机整数，默认0-1，一个参数返回0到指定范围(0-0总是返回0)
     * @param {number} num1 
     * @param {number} num2 
     */
    static randomInt(num1, num2) {
        num1 = isNaN(parseInt(num1, 10)) ? 1 : parseInt(num1, 10);
        num2 = isNaN(parseInt(num2, 10)) ? 0 : parseInt(num2, 10);
        let min = this.minNumber(num1);
        let max = this.maxNumber(num2);
        return min + Math.floor(Math.random() * (max - min + 1));
    }

    /**
     * 判断输入是否为0和正整数
     * @param {number} num 
     */
    static isInt(num) {
        let pattern = /^[0-9]$/;
        return typeof num === 'number' && pattern.test(num);
    }

    /**
     * 交换数组元素的位置 
     * @param {Array} array 
     * @param {Number} index1 
     * @param {Number} index2 
     */
    static arrayExchange(array, index1, index2) {
        if (!Array.isArray(array) || !this.isInt(index1) || !this.isInt(index2)) {
            throw Error("Require an array and two integers");
        }
        if (index1 >= array.length || index2 >= array.length) {
            throw Error("Index must be smaller than array's length");
        }

        let temp = array[index1];
        array[index1] = array[index2];
        array[index2] = temp;
    }

    /**
     * 返回当前数组的浅拷贝副本
     * @param {Array} array 
     */
    static arrayCopy (array){
        if(!Array.isArray(array)){
            throw Error("Require an array");
        }
        return array.slice();
    }

    /**
     * 将数组随机排序，返回新数组
     * @param {Array} array 
     */
    static shuffle(array) {
        if (array == undefined || !Array.isArray(array)) {
            throw Error("Need an array");
        }

        let resultArray = [];
        let arrayCopy = this.arrayCopy(array);
        while (arrayCopy.length) {
            let index = this.randomInt(arrayCopy.length - 1);
            this.arrayExchange(arrayCopy, index, arrayCopy.length - 1);
            resultArray.push(arrayCopy.pop());
        }
        return resultArray;
    }
}

module.exports = Utility;